//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-10-04  Jed Young  Creation
//

using chunmapModel
using chunmapData
using gfx2
using gfx
using gfx2Imp
using web
using chunmapView
using chunmapRaster

**
** TileService
**
const class TileService : WebMod
{
  const Unsafe layers
  const ImageCache cache
  const Grid grid
  const Size size

  new make(LayerList list, Int width := 512)
  {
    layers = Unsafe(list)
    this.cache = ImageCache.create
    grid = Grid(list.envelope)
    h := width * list.envelope.height / list.envelope.width
    this.size = Size(width, h.toInt)
  }

  override Void onService()
  {
    key := req.uri.query["key"]
    if (key == null)
    {
      res.headers["Content-Type"] = "text/plain"
      res.out.print(grid)
      res.out.print(";$size")
      return
    }
    image := getImage(key)

    type := MimeType.forExt("png")
    res.headers["Content-Type"] = type.toStr
    image.save(res.out, type)
  }

  Image2 getImage(Str key)
  {
    //try get cache
    image := cache.get(key)
    if(image != null) return image

    //using AWT
    Gfx2.setEngine("AWT")

    tile := grid.tile(key)

    // renderMap
    map := CMap(size, 1, 1)
    map.layers = layers.val

    map.view.setViewEnvelope(tile.envelope)
    //map.fullView
    map.render
    image = map.image

    cache.set(key, image)
    return image
  }
}